<?php
/**
 * Created by PhpStorm
 * User: Jhinwy
 * Date: 8/8/24
 * Time: 2:00 PM
 */

namespace app\common\service\video;


use OSS\OssClient;
use think\facade\Log;

class OssVideoService
{

    protected $bucket;
    protected $accessKey;
    protected $secretKey;
    protected $endpoint;
    protected $domain;

    protected $client;

    public function __construct()
    {
        $this->accessKey = config('oss.oss.access_key');
        $this->secretKey = config('oss.oss.secret_key');
        $this->domain    = config('oss.oss.domain');
        $this->bucket    = config('oss.oss.bucket');
        $this->endpoint  = config('oss.oss.endpoint');

        $this->client = $this->setClient();
    }


    /**
     * 连接OSS
     *
     * @return OssClient
     */
    protected function setClient()
    {
        try {
            return new OssClient($this->accessKey, $this->secretKey, $this->endpoint);
        } catch (\Exception $exception) {
            Log::write('连接OSS失败：' . $exception->getMessage(), 'error');
        }
    }


    /**
     * 上传视频
     *
     * @param $skitsId
     * @param $episodesOrder
     * @param $video
     * @return bool
     */
    public function uploadVideo($skitsId, $episodesOrder, $path, $video)
    {
        try {
            $this->client->putObject(
                $this->bucket,
                $this->getVideoPath($skitsId, $episodesOrder, $video),
                file_get_contents($path)
            );

            return true;
        } catch (\Exception $exception) {
            Log::write('上传视频失败：' . $exception->getMessage(), 'error');

            return false;
        }
    }


    /**
     * 获取视频路径
     *
     * @param $skitsId
     * @param $episodesOrder
     * @param $video
     * @return string
     */
    public function getVideoPath($skitsId, $episodesOrder, $video)
    {
        return 'video/' . $skitsId . '/' . $episodesOrder . '/' . $video;
    }


    /**
     * 获取视频链接
     *
     * @param $skitsId
     * @param $episodesOrder
     * @param $video
     * @return string
     */
    public static function getVideoUrl($skitsId, $episodesOrder, $video)
    {
        return config('oss.oss.domain') . '/video/' . $skitsId . '/' . $episodesOrder . '/' . $video;
    }
}
